package com.java;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 请举例说明集合类是线程不安全的
 * <p>
 * 1.故障现象
 * java.util.ConcurrentModificationException
 * <p>
 * 2.导致原因
 * <p>
 * 3.解决方案
 * 3.1   Vector
 * 3.2   Collections.synchronizedList(new ArrayList<>())
 * 3.3   CopyOnWriteArrayList
 * <p>
 * 4.优化建议（同样的错误，不出现第二次）
 *
 * @author jingjintao
 * @date 2021/10/24 - 15:33
 * 将代码抽取成一个方法快捷键: ctrl+alt+m
 **/
public class NotSafeDemo {

    public static void main(String[] args) {
        /*List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");

        for (String element : list) {
            System.out.println(element);
        }*/

        Map<String, String> map = new ConcurrentHashMap();//Collections.synchronizedMap(new HashMap<>());//new HashMap<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, i + "").start();
        }
        new HashMap<>();
    }

    private static void setNotSafe() {
        Set<String> set = new CopyOnWriteArraySet<>();//Collections.synchronizedSet(new HashSet<>());//new HashSet<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, i + "").start();
        }
    }

    private static void listNotSafe() {
        List<String> list = new CopyOnWriteArrayList<>();//Collections.synchronizedList(new ArrayList<>());//new Vector<>();//new ArrayList<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, i + "").start();
        }
    }
}
